//index.js
const app = getApp()

Page({
  /**
   * mode: none 、 general 、 manage 、 managelist 、 success
   */
  data: {
    mode: 'none',
    tableId: '',
    tableName: '',
    questions: []
  },

  onLoad: function (options) {
    if (options.scene) {
      this.initTable(options.scene);
    } else {
      this.initTable("0.23412010_1591931254748");
    }
  },

  /* --用户视图start-- */

  setAnswer: function (e) {
    var questions = this.data.questions
    questions[e.currentTarget.dataset.idx]['answer'] = e.detail.value
    this.data.questions = questions
  },

  submit: function () {
    let that = this;
    wx.showLoading({
      title: '提交中...',
      mask: true
    })

    const doc = {
      _id: `${Math.random()}_${Date.now()}`,
      table_id: that.data.tableId,
      table_name: that.data.tableName,
      data: that.data.questions
    }

    const db = wx.cloud.database()
    db.collection('q_data').add({
      data: doc,
      success: res => {
        that.setData({
          mode: 'success'
        })
        wx.hideLoading({})
      },
      fail: res => {
        that.setData({
          mode: 'none'
        })
        wx.hideLoading({})
      }
    })
  },

  /* go to management */

  aboutUs: function () {
    wx.showModal({
      title: '关于我们',
      confirmText: '关闭',
      cancelText: '后台',
      content: '程序名：爱安特问卷助手\n版权方：天津爱安特精密机械有限公司\n版本号：v1.1.1\n联系地址：antit@ant-fa.com',
      success: res => {
        if(res.cancel) {
          wx.navigateTo({
            url: '../manage/check/check',
          })
        }
      }
    })
  },

  /* else */
  initTable: function (tableId) {
    let that = this;
    wx.showLoading({
      title: '加载中...',
      mask: false
    })
    const db = wx.cloud.database();
    db.collection('q_table').where({
      _id: tableId
    }).get({
      success: res => {
        if (res.errMsg == 'collection.get:ok') {
          wx.setNavigationBarTitle({
            title: res.data[0].tableName,
          })
          that.setData({
            mode: 'general',
            tableId: tableId,
            tableName: res.data[0].tableName,
            questions: res.data[0].content
          })
        } else {
          that.setData({
            mode: 'none'
          })
        }
        wx.hideLoading({})
      },
      fail: res => {
        that.setData({
          mode: 'none'
        })
        wx.hideLoading({})
      }
    })
  },

})